<template>
    <base-breadcrumb :title="$route.meta.title">
        <!-- BIM培训台账编辑 -->
        <a-form-model
                ref="ruleForm"
                :model="form"
                :label-col="{ span: 6 }"
                :wrapper-col="{ span: 18 }"
                :rules="editModel != 0 ? rules : {}"
                id="base-breadcrumb"
                style="position: relative"
        >
            <a-spin :spinning="loading">
                <!-- 基本信息 -->
                <a-card :bordered="false" style="margin-bottom: 50px">
                    <title-name title="基本信息"></title-name>
                    <custom-form
                            :isEmit="false"
                            :formList="formList"
                            :form="form"
                            :editModel="editModel === 0 ? 'V' : ''"
                            :formComponents="$refs"
                    ></custom-form>
                    <!-- 页脚操作栏 -->
                    <div class="btn_box page-btn-right-top">
                        <a-button :loading="loading" v-if="editModel != 0" type="primary" class="button_right" @click="handleSubmit"
                        >提交</a-button
                        >
                        <a-button v-if="checkVisibleInDetail" type="primary" @click="handleActiveClose">关闭</a-button>
                    </div>
                </a-card>
            </a-spin>
        </a-form-model>
    </base-breadcrumb>
</template>

<script>
  import {
    insertBimTrain,
    updateBimTrain,
    getBimTrainLedgerById,
    getPageTypesLabel
  } from '@/api/bimIntegrate/bimResource'
  import BaseEditPage from '@/views/baseEditPage' // 编辑详情页基础配置
  import SelectCompanyAndProject from '@/components/Select/SelectCompanyAndProject'
  import Selector from '@/components/Select/Selector'

  export default {
    name: 'a' + Date.now(),
    extends: new BaseEditPage(),
    data() {
      return {
        trainOptions: [],
        loading: false, // 草稿和提交按钮loding
        editModel: 0, // 操作状态:0 查看;1 编辑;2 新增
        id: '', // 业务id
        form: {
          unitId: '', // 单位id
          unitName: '', // 单位
          // userId: '', //填写人ID
          // userName: '' //填写人姓名
        }, // 表单
        rules: {
          joinTrainUnit: [{ required: true, whitespace: true, message: '请输入参培单位', trigger: 'change' }],
          trainTime: [{ type: 'array', required: true, message: '请选择培训时间', trigger: 'change' }],
          unitId: [{ required: true, message: '请选择单位', trigger: 'change' }],
          // userId: [{required: true, message: '请选择填报人', trigger: 'change'}],
          organizerId: [{ required: true,  message: '请选择组织方', trigger: 'change' }],
          lecturer: [{ required: true, whitespace: true, message: '请输入授课人', trigger: 'change' }],
          numberOfPeople: [{ required: true, message: '请输入参培人数', trigger: 'change' }],
          trainName: [{required: true,message: '请输入培训名称',trigger: 'change'}],
          totalClasshours: [{ required: true, message: '请输入总学时', trigger: 'change' }],
          averageClasshours: [{ required: true, message: '请输入人均学时', trigger: 'change' }],
          periodsNumber: [{required: true,message: '请输入期数',trigger: 'change'}],
          trainExpenses: [{required: true,message: '请输入费用',trigger: 'change'}],
          placeForTraining: [{ required: true, whitespace: true, message: '请输入培训地点', trigger: 'change' }],
          trainingForm: [{ required: true, whitespace: true, message: '请输入培训形式', trigger: 'change' }],
          category: [{ required: true, message: '请选择培训形式', trigger: 'change' }],
          trainContentId: [{ required: true, message: '请选择培训分类', trigger: 'change' }],
          createTime: [{ required: true, message: '请选择借阅日期', trigger: 'change' }],
          fileInfoList: [{ type: 'array', required: true, message: '请上传文件', trigger: 'blur' }]
        }
      }
    },
    mounted() {
      this.trainTypesLabel()
      this.$route.meta.title = ['培训台账查看', '培训台账编辑', '培训台账新增'][this.editModel]
      // 不为添加时请求详情
      if (this.editModel != 2) {
        this.loading = true
        getBimTrainLedgerById({
          id: this.id
        })
          .then((res) => {
            this.loading = false
            if (res.code === '0') {
              res.data.startDate && res.data.endDate && (res.data.trainTime = [res.data.startDate, res.data.endDate])
              this.form = res.data
            }
          })
          .catch(() => {
            this.loading = false
          })
      } else {
        // this.$set(this.form, 'createTime', this.$dateFormat(new Date(), 'D'))
        this.form.unitName = this.$currentPost()?.name // 默认单位
        this.form.unitId = this.$currentPost()?.id // 默认单位id
        // this.form.userId = this.$userInfo()?.employee.id
        // this.form.userName = this.$userInfo()?.employee.name
      }
    },
    computed: {
      // 表单列表
      formList() {
        return [
          {
            keyName: 'organizerId',
            viewName: 'organizer',
            label: '举办单位',
            type: SelectCompanyAndProject,
            attrs: {
              extraParams: {
                notContainTags: ['PD']
              }
            },
            onSelectChange: (e) => {
              this.form.organizer = e.name
            }
          },
          {
            keyName: 'trainContentId',
            viewName: 'trainContent',
            type: Selector,
            attrs: {
              customApi: getPageTypesLabel,
              customQuery: { param: { type: '39' } },
              dataValue: 'data.list',
              filterFn: (item)=>{
                //item.id = Number(item.id)
                return true
              }
            },
            label: '培训分类',
            getOption: (e) => {
              // 映射奖项名称name
              this.form.trainContent = e?.name
            }
          },
          {
            keyName: 'trainName',
            type: 'BaseInput',
            label: '培训名称'
          },
          {
            keyName: 'numberOfPeople',
            type: 'BaseInputNumber',
            label: '参培人数',
            precision: 0,
            attrs: {
              min: 1,
            }
          },
          {
            keyName: 'lecturer',
            type: 'BaseInput',
            label: '授课人'
          },
          {
            keyName: 'placeForTraining',
            type: 'BaseInput',
            label: '培训地点'
          },
          {
            keyName: 'periodsNumber',
            type: 'BaseInputNumber',
            label: '期数',
            precision: 0,
            attrs: {
              min: 1
            }
          },
          {
            keyName: 'trainExpenses',
            type: 'BaseInputNumber',
            label: '费用(元)',
            precision: 0,
            attrs: {
              min: 1
            }
          },
          {
            keyName: 'category',
            viewName: 'categoryName',
            type: 'a-select',
            label: '培训形式',
            data: [
              {
                label: '现场',
                value: 0
              },
              {
                label: '线上',
                value: 1
              },
              {
                label: '现场+线上',
                value: 2
              }
            ],
            customRender(e) {
              return ['现场', '线上','现场+线上'][e] || '无'
            },
            change: (e) => {
              // 映射类别name
              this.form.categoryName = ['现场', '线上','现场+线上'][e]
            }
          },
          {
            keyName: 'trainTime',
            type: 'a-range-picker',
            label: '培训时间',
            attrs: {
              valueFormat: 'YYYY-MM-DD'
            },
            customRender(e) {
              return e?.length === 2 ? e[0] + '~' + e[1] : '无'
            }
          },
          {
            keyName: 'averageClasshours',
            type: 'BaseInputNumber',
            label: '人均学时',
            precision: 0,
            attrs: {
              min: 1
            }
          },
          {
            keyName: 'fileInfoList',
            type: 'uploadFile',
            label: '附件',
            span: 24,
            remark: '请上传培训通知、参训名单、培训照片、签到表、授课课件、培训评价表等相关附件',
            hiddenRemark: true,
            businessCode: 'BIM02',
          },
        ]
      },
    },
    methods: {
      trainTypesLabel(){
        getPageTypesLabel({ param: { type: '39' } })
          .then((e)=>{
            if(e.code ==='0'){
               this.trainOptions = e.data.list
            }
          })
      },
      /**
       * 提交表单
       */
      handleSubmit() {
        let that = this
        let url = [updateBimTrain, insertBimTrain][that.editModel - 1] // 根据操作切换url地址
        console.log('url=',url)
        // 校验表单
        that.$refs.ruleForm.validate((e) => {
          console.log('e=',e)
          if (e) {
            // 提交表单
            that.loading = true
            let form = that.$clone(that.form)
            // 格式化培训时间
            if (form.trainTime?.length === 2) {
              form.startDate = form.trainTime[0]
              form.endDate = form.trainTime[1]
            }
            console.log('form=',form)
            url(form)
              .then((res) => {
                console.log(res)
                that.loading = false
                if (res.code === '0' || res.data.code === '0') {
                  that.$message.success('提交成功！')
                  that.$multiTab.close()
                }
              })
              .catch((res) => {
                that.loading = false
              })
          }
        })
      }
    }
  }
</script>
